<?php

class BaseModel extends CActiveRecord
{
	/**
	 * toArray 将ActiveRecord对象装换成关联数组	 *
	 * @param BaseModel $this 要转换的对象
	 * @param array $with 需要关联转换的关系	 * @access public
	 * @return array
	 */
	public function toArray($_with = array()) {
		if(!is_array($_with)) {
			$_with = array($_with);
		}

		$with = array();
		foreach($_with as $k => $w) {
			if(is_int($k)) {
				$with[] = $w;
			}
			else {
				$with[] = $k;
			}
		}

		if(is_array($this)) {
			$ret = array();
			foreach ($this as $tmp) {
				$ret[] = $tmp->singleModelToArray($with);
			}
			return $ret;
		}
		elseif(is_object($this)) {
			return $this->singleModelToArray($with);
		}
		else {
			return null;
		}
	}

	/**
	 * singleModelToArray 转换单个对象为关联数组	 *
	 * @param BaseModel $this 要转换的对象
	 * @param array $with 需要关联转换的关系	 * @access private
	 * @return array
	 */
	private function singleModelToArray($with) {
		$ret = $this->getAttributes();
		$relations = $this->relations();

		foreach($with as $r) {
			if(isset($relations[$r])) {
				$rModel = $this->$r;
				if(is_array($rModel)) {
					$ret[$r] = array();
					foreach($rModel as $t) {
						$ret[$r][] = $t->getAttributes();
					}
				}
			}
			else {
				$rModel = $this->$r;
				if($rModel) {
					$ret[$r] = $rModel->getAttributes();
				}
				else {
					$ret[$r] = null;
				}
			}
		}

		return $ret;
	}
}
